package gugga.tasks
{
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.TimerEvent;
	import flash.utils.Timer;
	
	import gugga.tasks.events.TaskEvent;
	
	[Event(name="start", type="TaskEvent")]
	[Event(name="interrupted", type="TaskEvent")]
	[Event(name="completed", type="TaskEvent")]
	
	/**
	 * <code>WaitingTask</code> is a task, that completes after a specified time interval set in seconds.
	 */
	public class WaitingTask extends EventDispatcher implements ITask
	{
		private var mWaitInterval : Number; //in seconds
		private var mIntervalID : Number;
		
		private var mTimer : Timer;
		
		private var mIsRunning:Boolean;
		
		/**
		 * @param aWaitInterval in seconds. Default value is 0.01 seconds
		 */ 
		public function WaitingTask(aWaitInterval : Number = 0.01)
		{
			mWaitInterval = aWaitInterval;
			
			mIsRunning = false;
		}
		
		public function start() : void 
		{
			mIsRunning = true;
			dispatchEvent(new TaskEvent(TaskEvent.START));
			
			if(mWaitInterval > 0)
			{
				mTimer = new Timer(1000 * mWaitInterval, 1)
				mTimer.addEventListener(TimerEvent.TIMER, onTimerElapsed);
				mTimer.start();
			}
			else
			{
				mIsRunning = false;
				dispatchEvent(new TaskEvent(TaskEvent.COMPLETED));
			}
		}
		
		public function isRunning() : Boolean 
		{
			return mIsRunning;
		}
		
		public function isImmediatelyInterruptable() : Boolean
		{
			return true;
		}
		
		public function interrupt() : void
		{
			mTimer.stop();
			mIsRunning = false;
			dispatchEvent(new TaskEvent(TaskEvent.INTERRUPTED));
		}
		
		private function onTimerElapsed(aEvent : Event) : void
		{
			mIsRunning = false;
			dispatchEvent(new TaskEvent(TaskEvent.COMPLETED));
		}
	}
}